package io.adminboot.service.impl;

import io.adminboot.entity.SysMenu;
import io.adminboot.entity.SysUser;
import io.adminboot.entity.SysUserToken;
import io.adminboot.entity.SysUserTokenExample;
import io.adminboot.repository.SysUserTokenMapper;
import io.adminboot.service.ShiroService;
import io.adminboot.service.SysMenuService;
import io.adminboot.service.SysUserService;
import io.adminboot.utils.Constant;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class ShiroServiceImpl implements ShiroService {
	
	@Autowired
	private SysUserTokenMapper mapper;
    
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysMenuService menuService;

    @Override
    public Set<String> getUserPermissions(long userId) {
        List<String> permsList;

        //系统管理员，拥有最高权限
        if(userId == Constant.SUPER_ADMIN){
            List<SysMenu> menuList = menuService.queryAll();
            permsList = new ArrayList<>(menuList.size());
            for(SysMenu menu : menuList){
                permsList.add(menu.getPerms());
            }
        }else{
            permsList = userService.queryAllPerms(userId);
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String perms : permsList){
            if(StringUtils.isBlank(perms)){
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

    @Override
    public SysUserToken queryByToken(String token) {
    	SysUserTokenExample example = new SysUserTokenExample();
    	example.createCriteria().andTokenEqualTo(token);
    	List<SysUserToken> list = mapper.selectByExample(example);
        return CollectionUtils.isEmpty(list) ? null : list.get(0);
    }

    @Override
    public SysUser queryUser(Long userId) {
        return userService.queryById(userId);
    }
}
